import { MutationTree, ActionTree, ActionContext } from 'vuex'
import { ActionTypes, MutationTypes } from './types'
export const state = {
  counter: 0,
}
export type State = typeof state

export const mutations: MutationTree<State> = {
  [MutationTypes.SET_COUNTER](state, payload: number) {
    state.counter = payload
  },
}

import { GetterTree } from 'vuex'

export type Getters = {
  doubledCounter(state: State): number
}

export const getters: GetterTree<State, State> & Getters = {
  doubledCounter: (state) => {
    return state.counter * 2
  },
}

type AugmentedActionContext = {
  commit<K extends MutationTypes>(key: K, payload: number): void
} & Omit<ActionContext<State, State>, 'commit'>

export interface Actions {
  [ActionTypes.GET_COUTNER](
    { commit }: AugmentedActionContext,
    data: number
  ): Promise<number>
}

export const actions: ActionTree<State, State> & Actions = {
  [ActionTypes.GET_COUTNER]({ commit }, data) {
    return new Promise((resolve) => {
      setTimeout(() => {
        commit(MutationTypes.SET_COUNTER, data)
        resolve(data)
      }, 500)
    })
  },
}
